package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 关注和取关
     *
     * @param id
     * @param istrue
     * @return
     */
    @Override
    public Result follow(Long id, Boolean istrue) {

        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String KEY = "follow:" + userId;
        //2.判断是否关注
        if (istrue) {
            //3.未关注(istrue==true)：添加关注信息到数据库，并且储存到redis的set中（当前用户id，关注的用户id）
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(id);
            boolean success = save(follow);
            if (success) {
                stringRedisTemplate.opsForSet().add(KEY, id.toString());
            }
        } else {
            //4.关注(istrue==false)：将数据库内的关注信息删除，并且将redis中的数据删除
            boolean success = remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", id));
            if (success) {
                stringRedisTemplate.opsForSet().remove(KEY, id.toString());
            }
        }
        return Result.ok();
    }


    /**
     * 判断用户是否关注了该用户
     *
     * @param id
     * @return
     */
    @Override
    public Result checkFollow(Long id) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询数据库看是否有数据
        Integer count = query().eq("user_id", userId).eq("follow_user_id", id).count();
        //3.查询到了：表示已关注

        //4.未查询到：未关注
        return Result.ok(count > 0);
    }


    /**
     * 实现共同关注功能（利用set的取交集（key1，key2））
     *
     * @param id
     * @return
     */
    @Override
    public Result commonFollow(Long id) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.取交集
        String KEY = "follow:" + userId;
        String KEY2 = "follow:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(KEY, KEY2);
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //3.封装为userDTO对象
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOS = userService.listByIds(ids).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
